
package com.newenergy.wisehome.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.newenergy.wisehome.R;


public class ColorPickerView extends FrameLayout {

    private ImageView iv_color_range;//颜色选择盘

    private ImageView iv_color_picker;//颜色选择器

    private RelativeLayout rl_root;//根布局

    private int range_radius;//圆盘半径
    private int picker_radius;//颜色选择器半径
    private int centreX;//圆盘中心X坐标
    private int centreY;//圆盘中心Y坐标
    private int picker_centreX;//颜色选择器中心X坐标
    private int picker_centreY;//颜色选择器中心Y坐标
    private Bitmap bitmap;//颜色选择盘图片

    private float mDensity;


    public int lastX = 0, lastY = 0;//上次触摸坐标
    private OnColorChangedListener colorChangedListener;//颜色变换监听
    private Context mContext;

    public ColorPickerView(Context context) {
        super(context);
        init(context);

    }

    public ColorPickerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        mDensity = context.getResources().getDisplayMetrics().density;
        mContext = context.getApplicationContext();
        View view = LayoutInflater.from(context).inflate(R.layout
                .color_picker, this);
        iv_color_range = (ImageView) view.findViewById(R.id
                .iv_color_range);
        iv_color_picker = (ImageView) view.findViewById(R.id
                .iv_color_picker);
        rl_root = (RelativeLayout) view.findViewById(R.id.rl_root);
        setColourDiskTouchListener();
        setPickerTouchListener();
        initBItMap();

    }

    //位置
    public void setPickerLocation(int centerX, int centerY) {
//        LogHelper.i("setPickerLocation:centerX=" + centerX + "  " + "centerY=" + centerY);

        centerX = (int) (mDensity * centerX);
        centerY = (int) (mDensity * centerY);
        iv_color_picker.layout(centerX - picker_radius, centerY -
                picker_radius, centerX + picker_radius, centerY +
                picker_radius);
        invalidate();
    }

    private void getViewData() {
        initViewData();
        //133dp
        int r1 = (int) (iv_color_range.getWidth() / 2 / mDensity);
//        LogHelper.i("ViewTree r1=" + r1);
    }


    private void setPickerTouchListener() {
        //选择器触摸监听
        iv_color_picker.setOnTouchListener((v, event) -> {
            initViewData();
            int ea = event.getAction();
            initViewData();
            switch (ea) {
                case MotionEvent.ACTION_DOWN://按下
//                    LogHelper.i("手指按下");
                    lastX = (int) event.getRawX();
                    lastY = (int) event.getRawY();
                    colorChangedListener.startDown();
                    getParent().requestDisallowInterceptTouchEvent (true);


                    //通知父控件勿拦截本控件touch事件break;
                case MotionEvent.ACTION_MOVE://拖动
                    getRgbHexs(v, event);
                    break;
                case MotionEvent.ACTION_UP://抬起
                    if (colorChangedListener==null)return true;
                    colorChangedListener.stopMove();
//                    Log.e("LFX","setPickerTouchListener抬起");
                    getRgbHexs(v, event);

            }
            return true;
        });
    }

    private void printViewParmas(View view, String name) {
//        LogHelper.i(name + "  x=" + view.getX() + "  y=" + view
//                .getY() + "  width=" + view.getWidth() + "  " +
//                "Height=" + view.getHeight());
//        LogHelper.i(name + "  left=" + view.getLeft() + "  top=" +
//                view.getTop() + "  right=" + view.getRight() + "
// " +
//                "bottom=" + view.getBottom());

    }


    private void getRgbHexs(View v, MotionEvent event) {
        //拖动距离
        int dx = (int) event.getRawX() - lastX;
        int dy = (int) event.getRawY() - lastY;
        //相对于父控件的新坐标
        int left = v.getLeft() + dx;
        int top = v.getTop() + dy;
        int right = v.getRight() + dx;
        int bottom = v.getBottom() + dy;


        //选择器圆心坐标
        picker_centreX = right - picker_radius;
        picker_centreY = bottom - picker_radius;

        //选择器圆心与圆盘圆心距离
        float diff = (float) (Math.sqrt((centreY -
                picker_centreY) * (centreY -
                picker_centreY) + (centreX -
                picker_centreX) *
                (centreX - picker_centreX)) +
                picker_radius / 2 + mDensity * 8);//两个圆心距离+颜色选择器半径
        //在圆内，则拖动
        if (diff <= range_radius) {
            v.layout(left, top, right, bottom);


//            printViewParmas(v, "getRgbHexs View 后");
            invalidate();
//            LogHelper.i("diff=" + diff);
            if (diff <= mDensity * 20) {
                if (colorChangedListener != null) {
                    colorChangedListener.notifyColorChanged(255,
                            255, 255);
                    notifyPickerCenterChanged();
                }
            } else {
                notifyColorChanged();
            }

            lastX = (int) event.getRawX();
            lastY = (int) event.getRawY();
        }
        getParent()
                .requestDisallowInterceptTouchEvent
                        (true);//通知父控件勿拦截本控件touch事件
    }

    public void notifyPickerCenterChanged() {
        int centerX = (int) (picker_centreX / mDensity);
        int centerY = (int) (picker_centreY /
                mDensity);
        if (colorChangedListener != null) {
            colorChangedListener.pickerCenterChanged(centerX,centerY);
        }
    }


    private void notifyColorChanged() {
        int pixel = bitmap.getPixel
                (picker_centreX - iv_color_range
                                .getLeft(),
                        picker_centreY -
                                iv_color_range
                                        .getTop
                                                ());
        //获取选择器圆心像素
        if (colorChangedListener != null) {//读取颜色
            colorChangedListener.notifyColorChanged
                    (Color.red(pixel), Color
                            .blue(pixel), Color
                            .green(pixel));

            notifyPickerCenterChanged();
        }
    }


    private void initViewData() {
        if (range_radius == 0) {//未初始化
            range_radius = iv_color_range.getWidth() / 2;
            //圆盘半径
            picker_radius = iv_color_picker.getWidth() / 2;
            //选择器半径
            centreX = iv_color_range.getRight() -
                    range_radius;
            centreY = iv_color_range.getBottom() -
                    iv_color_range.getHeight() / 2;
        }
    }



    private void initBItMap() {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = false;
        // Do not compress
        newOpts.inSampleSize = 1;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        bitmap = BitmapFactory.decodeResource(mContext
                .getResources(), R.drawable.color_800,newOpts);
    }


    @SuppressLint("ClickableViewAccessibility")
    private void setColourDiskTouchListener() {
        iv_color_range.setOnTouchListener((v, event) -> {
            initViewData();
            int cd = event.getAction();
            initViewData();
            switch (cd) {
                case MotionEvent.ACTION_DOWN://按下
                    int width = v.getWidth();
                    int x = (int) event.getX();
                    int y = (int) event.getY();
                    int cx = (int) (width * 0.5 + 0.5);
                    int r = (int) (width * 0.5 + 0.5);
                    boolean b = pointIsInCircle(x, y, cx);
                    if (!b) return false;

                    int[] location = new int[2];
                    iv_color_picker.getLocationOnScreen(location);
                    lastX = location[0];
                    lastY = location[1];
                    /*lastX = (int) event.getRawX();
                    lastY = (int) event.getRawY();*/
                    colorChangedListener.startDown();
                    getParent() .requestDisallowInterceptTouchEvent (true);

                    //通知父控件勿拦截本控件touch事件break;
                case MotionEvent.ACTION_MOVE://拖动
                    getRgbHexs(iv_color_picker, event);
                    break;
                case MotionEvent.ACTION_UP://抬起
                    if (colorChangedListener==null)return true;
                    colorChangedListener.stopMove();
                    getRgbHexs(iv_color_picker, event);

            }
            return true;
        });

    }

    private void printEventParmas(MotionEvent event, String name) {

//        LogHelper.i(name + "  X=" + event.getX() + "  Y=" + event
//                .getY() + "  RawX=" + event.getRawX() + "  RawY=" +
//                event.getRawY());

    }


    public void setColorChangedListener(OnColorChangedListener colorChangedListener) {
        this.colorChangedListener = colorChangedListener;
    }


    /**
     * 颜色变换监听接口
     */
    public interface OnColorChangedListener {
        void startDown();
        void notifyColorChanged(int red, int blue, int green);

        void stopMove();

        void pickerCenterChanged(int centerX, int centerY);
    }


    /**
     * 判断点击的位置是否在圆内
     *
     * @param x
     * @param y
     * @param cx 圆点的x坐标
     * @return
     */

    public boolean pointIsInCircle(float x, float y, float cx) {
        float len = (x - cx) * (x - cx) + (y - cx) * (y - cx);
        boolean b = (len <= (cx * cx));
        return b;
    }

    public void destroyBitmap(){
        if (bitmap!=null&& !bitmap.isRecycled())
        bitmap.recycle();
        bitmap=null;
        //获取view在屏幕的位置
        getViewTreeObserver().removeOnGlobalLayoutListener(() -> getViewData() );

    }
}

